import { createReducer, ActionType, createAsyncAction, createAction } from 'typesafe-actions';
import { Dispatch } from 'redux';
import Axios from 'axios';

import { TreeNodeNormal } from 'antd/lib/tree/Tree';
import _ from 'lodash';

export interface WordSourceNodeDto {
    wordSourceId: number
    wordSourceValue: string
}
export interface WordSourceState {
    dto: TreeNodeNormal
    currentId: number
    currentIdInner: number | null
}

const fetchActions = createAsyncAction(
    'WORD_SOURCE/FETCH/REQUEST',
    ['WORD_SOURCE/FETCH/SUCCESS', (res: TreeNodeNormal) => res],
    ['WORD_SOURCE/FETCH/FAILURE', (err: Error) => err],
    'WORD_SOURCE/FETCH/CANCEL',
)();

export const setCurrentId = createAction('WORD_SOURCE/SET_CURRENT_ID')<number>();
export const setCurrentIdInner = createAction('WORD_SOURCE/SET_CURRENT_ID_INNNER')<number | null>();


export const fetch = (): any =>
    async (dispatch: Dispatch) =>
        Axios.get<TreeNodeNormal>('wordSource/')
            .then((response) => { dispatch(fetchActions.success(response.data)) })
            .catch(error => dispatch(fetchActions.failure(error)))

//接下来几个操作直接请求fetch state，不直接修改state

export const add = (vo: WordSourceNodeDto) =>
    async (dispatch: Dispatch) =>
        Axios.post(`wordSource/${vo.wordSourceId}/${vo.wordSourceValue}`)
            .then(() => dispatch(fetch()))

export const edit = (vo: WordSourceNodeDto) =>
    async (dispatch: Dispatch) =>
        Axios.put(`wordSource/${vo.wordSourceId}/${vo.wordSourceValue}`)
            .then(() => dispatch(fetch()))

export const remove = (vo: WordSourceNodeDto) =>
    async (dispatch: Dispatch) =>
        Axios.delete(`wordSource/${vo.wordSourceId}`)
            .then(() => dispatch(fetch()))

export type Actions = ActionType<typeof fetchActions>
    | ActionType<typeof setCurrentId>
    | ActionType<typeof setCurrentIdInner>
    ;

const initialState: WordSourceState = {
    dto: {
        key: '-1',
        title: '空'
    },
    currentId: -1,
    currentIdInner: null,
};

//配置action回写state中心的部分
export const Reducer = createReducer<WordSourceState, Actions>(initialState)
    .handleAction(fetchActions.success, (state, action) => {
        const newState = _.cloneDeep(state)
        //所有key换成t开头
        newState.dto = JSON.parse(JSON.stringify(action.payload).replace(/"key":(\d*)/g, '"key":"t$1"'))
        return newState
    })
    .handleAction(setCurrentId, (state, action) => {
        const newState = _.cloneDeep(state)
        newState.currentId = action.payload
        return newState
    })
    .handleAction(setCurrentIdInner, (state, action) => {
        const newState = _.cloneDeep(state)
        newState.currentIdInner = action.payload
        return newState
    })

